package com.jinjiafeng.baselibrary.widget.indicator;

import android.content.Context;
import android.content.res.TypedArray;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;

import com.jinjiafeng.baselibrary.R;

/**
 * @author jinjiafeng
 * Time :18-6-3
 * 适配器模式获取count,view
 */
@SuppressWarnings("unchecked")
public class IndicatorView extends HorizontalScrollView implements ViewPager
        .OnPageChangeListener {
    private IndicatorContainerView mIndicatorContainer;
    private int mVisibleItemNumber = 4;
    private int mItemWidth;
    /**
     * 用来记录当前高亮的view
     */
    private int mCurrentPosition;
    private BaseIndicatorAdapter mAdapter;
    private ViewPager mViewPager;

    /**
     * 是否执行滚动
     */
    private boolean mExecuteScroll = false;

    public IndicatorView(Context context) {
        this(context, null);
    }

    public IndicatorView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public IndicatorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        final TypedArray array = context.obtainStyledAttributes(attrs, R.styleable
                .IndicatorView);
        mVisibleItemNumber = array.getInteger(R.styleable.IndicatorView_visibleNumber,
                mVisibleItemNumber);
        array.recycle();
        mIndicatorContainer = new IndicatorContainerView(context);
        addView(mIndicatorContainer);
    }


    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        super.onLayout(changed, l, t, r, b);
        if (changed) {
            final int childCount = mAdapter.getCount();
            this.mItemWidth = getItemWidth();
            for (int i = 0; i < childCount; i++) {
                final View child = mIndicatorContainer.getItemViewAt(i);
                final ViewGroup.LayoutParams params = child.getLayoutParams();
                params.width = mItemWidth;
                child.setLayoutParams(params);
            }
            mIndicatorContainer.addBottomTrackView(mAdapter.getBottomTrackView(), mItemWidth);
        }
    }

    private int getItemWidth() {
        if (mVisibleItemNumber != 0) {
            return getWidth() / mVisibleItemNumber;
        }
        int itemWidth;
        int maxWidth = 0;
        int allWidth;
        final int adapterCount = mAdapter.getCount();
        for (int i = 0; i < adapterCount; i++) {
            int currentWidth = mIndicatorContainer.getItemViewAt(i).getWidth();
            maxWidth = Math.max(currentWidth, maxWidth);
        }

        allWidth = maxWidth * adapterCount;
        itemWidth = maxWidth;
        if (allWidth < getWidth()) {
            itemWidth = getWidth() / adapterCount;
        }
        //最多可以显示几条
        final int count = getWidth() / maxWidth;
        final int residueWidth = (getWidth() - maxWidth * count) / count;
        return itemWidth + residueWidth;
    }

    public void setAdapter(BaseIndicatorAdapter adapter, ViewPager viewPager) {
        if (viewPager == null) {
            throw new NullPointerException("viewpager is null");
        }
        this.mViewPager = viewPager;
        viewPager.addOnPageChangeListener(this);
        setAdapter(adapter);
    }

    private void setAdapter(BaseIndicatorAdapter adapter) {
        if (adapter == null) {
            throw new NullPointerException("IndicatorAdapte can not be null");
        }
        this.mAdapter = adapter;

        final int count = adapter.getCount();
        for (int i = 0; i < count; i++) {
            final View view = mAdapter.getView(i, mIndicatorContainer);
            this.mIndicatorContainer.addItemView(view);
            setItemClick(view, i);
        }
        mAdapter.highlightView(mIndicatorContainer.getItemViewAt(0));
    }

    private void setItemClick(View view, final int i) {
        view.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mViewPager.setCurrentItem(i);
                mIndicatorContainer.smoothScrollBottomTrack(i);
            }
        });
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if (mExecuteScroll) {
            scrollIndicator(position, positionOffset);
            mIndicatorContainer.scrollBottomTrack(position, positionOffset);
        }
    }

    private void scrollIndicator(int position, float positionOffset) {
        final float finalWidth = (position + positionOffset) * mItemWidth;
        final int offsetWidth = (getWidth() - mItemWidth) / 2;
        scrollTo((int) (finalWidth - offsetWidth), 0);
    }

    @Override
    public void onPageSelected(int position) {
        mAdapter.restoreView(mIndicatorContainer.getItemViewAt(mCurrentPosition));
        mCurrentPosition = position;
        mAdapter.highlightView(mIndicatorContainer.getItemViewAt(mCurrentPosition));
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        //0->闲置
        if (state == 0) {
            mExecuteScroll = false;
            //1->用户滑动
        } else if (state == 1) {
            mExecuteScroll = true;
        }
    }

}
